﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using WebMassage.Models;
using WebMassage.Helpers;
using System.IO;

namespace WebMassage.Controllers
{
    public class KTVController : Controller
    {
        string ktvPath = AppDomain.CurrentDomain.BaseDirectory + @"\upload\KTV\";
        int defaultPageSize = 10;
        public ActionResult Index()
        {
            KTVInfoResponsitory ktvRes = null;
            try
            {
                ktvRes = new KTVInfoResponsitory();
                return View();
            }
            catch (Exception ex)
            {
                ViewData["Message"] = ex.Message;
                return View("../Shared/Error");
            }
            finally
            {
                if (ktvRes != null)
                    ktvRes.Dispose();
            }
        }

        public ActionResult KTVShow()
        {
            return View();
        }
        
        [Authorize(Roles = "Administrator")]
        public ActionResult Manager(int? page)
        {
            KTVInfoResponsitory ktvRes = null;
            try
            {
                ktvRes = new KTVInfoResponsitory();
                var ktvInfos = ktvRes.All();
                int pageIndex = page.HasValue ? page.Value - 1 : 0;
                return View(ktvInfos.ToPagedList(pageIndex, defaultPageSize));       
            }
            catch (Exception ex)
            {
                ViewData["Message"] = ex.Message;
                return View("../Shared/Error");
            }
            finally
            {
                if (ktvRes != null)
                    ktvRes.Dispose();
            }
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult Details(string ktvNum, int? page)
        {
            KTVInfoResponsitory ktvRes = null;
            try
            {
                ktvRes = new KTVInfoResponsitory();
                KTVInfo ktvInfo = ktvRes.GetByKTVNum(ktvNum).SingleOrDefault();
                KTVDetailViewModel viewModel = new KTVDetailViewModel();
                viewModel.KTV = ktvInfo;
                int pageIndex = page.HasValue ? page.Value - 1 : 0;
                viewModel.Pics = ktvInfo.KTVPics.ToPagedList(pageIndex, defaultPageSize);

                return View(viewModel);
            }
            catch (Exception ex)
            {
                ViewData["Message"] = ex.Message;
                return View("../Shared/Error");
            }
            finally
            {
                if (ktvRes != null)
                    ktvRes.Dispose();
            }
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [Authorize(Roles = "Administrator")]
        public ActionResult Create(FormCollection collection)
        {
            KTVInfoResponsitory ktvRes = null;
            try
            {
                ktvRes = new KTVInfoResponsitory();
                KTVInfo ktvInfo = new KTVInfo();

                try
                {
                    ktvInfo.KTVNum = collection["KTVNum"];
                    ktvInfo.Name = collection["Name"];
                    ktvInfo.Sex = collection["Sex"] == "1" ? true : false;
                    ktvInfo.ShowInHome = collection["ShowInHome.Value"] == "false" ? false : true;
                    ktvInfo.Size1 = collection["Size1"];
                    ktvInfo.Size2 = collection["Size2"];
                    ktvInfo.Size3 = collection["Size3"];
                    ktvInfo.Note = collection["Note"];

                    if (!string.IsNullOrEmpty(collection["Weight"]))
                        ktvInfo.Weight = int.Parse(collection["Weight"]);

                    if (!string.IsNullOrEmpty(collection["Height"]))
                        ktvInfo.Height = int.Parse(collection["Height"]);

                    ktvInfo.BirthDate = DateTime.Parse(collection["BirthDate"]);

                }
                catch 
                {
                    
                }
                
                ktvRes.Add(ktvInfo);
                ktvRes.Save();
                return RedirectToAction("Manager");
            }
            catch (Exception ex)
            {
                ViewData["Message"] = ex.Message;
                return View("../Shared/Error");
            }
            finally
            {
                if (ktvRes != null)
                    ktvRes.Dispose();
            }
        }
        
        [Authorize(Roles = "Administrator")]
        public ActionResult Edit(string ktvNum)
        {
            KTVInfoResponsitory ktvRes = null;
            try
            {
                ktvRes = new KTVInfoResponsitory();
                KTVInfo ktvInf = ktvRes.GetByKTVNum(ktvNum).SingleOrDefault();
                return View(ktvInf);
            }
            catch (Exception ex)
            {
                ViewData["Message"] = ex.Message;
                return View("../Shared/Error");
            }
            finally
            {
                if (ktvRes != null)
                    ktvRes.Dispose();
            }
        }

        [HttpPost]
        [Authorize(Roles = "Administrator")]
        public ActionResult Edit(string ktvNum, FormCollection collection)
        {
            KTVInfoResponsitory ktvRes = null;
            try
            {
                ktvRes = new KTVInfoResponsitory();
                KTVInfo ktvInfo = ktvRes.GetByKTVNum(ktvNum).SingleOrDefault() ;
                try
                {
                    ktvInfo.KTVNum = collection["KTVNum"];
                    ktvInfo.Name = collection["Name"];
                    ktvInfo.Sex = collection["Sex"] == "1" ? true : false;
                    ktvInfo.ShowInHome = collection["ShowInHome.Value"] == "false" ? false : true;
                    ktvInfo.Size1 = collection["Size1"];
                    ktvInfo.Size2 = collection["Size2"];
                    ktvInfo.Size3 = collection["Size3"];
                    ktvInfo.Note = collection["Note"];

                    if (!string.IsNullOrEmpty(collection["Weight"]))
                        ktvInfo.Weight = int.Parse(collection["Weight"]);

                    if (!string.IsNullOrEmpty(collection["Height"]))
                        ktvInfo.Height = int.Parse(collection["Height"]);

                    ktvInfo.BirthDate = DateTime.Parse(collection["BirthDate"]);

                }
                catch
                {

                }
                ktvRes.Save();
                return RedirectToAction("Manager");
            }
            catch (Exception ex)
            {
                ViewData["Message"] = ex.Message;
                return View("../Shared/Error");
            }
            finally
            {
                if (ktvRes != null)
                    ktvRes.Dispose();
            }
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult Delete(string ktvNum, int? page)
        {
            KTVInfoResponsitory ktvRes = null;
            KTVPicResponsitory ktvPicRes = null;
            try
            {
                ktvRes = new KTVInfoResponsitory();
                ktvPicRes = new KTVPicResponsitory();
                KTVInfo ktvInfo = ktvRes.GetByKTVNum(ktvNum).SingleOrDefault();
                if (ktvInfo != null)
                {
                  
                    ktvPicRes.Delete(ktvNum);
                    ktvPicRes.Save();
                    ktvRes.Delete(ktvInfo);
                    ktvRes.Save();

                    if (Directory.Exists(ktvPath + ktvNum))
                        Directory.Delete(ktvPath + ktvNum, true);
                }
                return RedirectToAction("Manager", new { page = page });
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (ktvRes != null)
                    ktvRes.Dispose();
            }            
        }
        
        [HttpPost]
        [Authorize(Roles = "Administrator")]
        public ActionResult UploadImage()
        {
            string ktvNum = Request.Form["KTVNum"];
            string ktvFolder = ktvPath + ktvNum + "\\";
            if (!Directory.Exists(ktvFolder))
            {
                Directory.CreateDirectory(ktvFolder);
            }
            KTVInfoResponsitory ktvInfos = new KTVInfoResponsitory();
            KTVPicResponsitory ktvPics = new KTVPicResponsitory();
            KTVInfo ktvInfo = ktvInfos.GetByKTVNum(ktvNum).SingleOrDefault();
            try
            {
                int i = ktvPics.GetByKtvNum(ktvNum).Count() + 1;
                foreach (string tagName in Request.Files)
                {
                    if (Request.Files[tagName] == null) continue; 
                    HttpPostedFileBase file = Request.Files[tagName];
                    string fileExt = "";
                    if (file.ContentLength > 0)
                    {
                        fileExt = Path.GetExtension(file.FileName);

                        if (fileExt.Length > 0)
                        {                            
                            file.SaveAs(ktvFolder + ktvNum + "-" + i + fileExt);
                            KTVPic ktvPic = new KTVPic();
                            ktvPic.KTVId = ktvInfo.KTVId;
                            ktvPic.PictureUrl = @"\upload\KTV\" + ktvNum + @"\" + ktvNum + "-" + i + fileExt;
                            ktvPic.Note = ktvInfo.Name;
                            ktvPics.Add(ktvPic);
                            ktvPics.Save();
                            i++;
                        }                        
                    }
                }
            }
            catch (Exception ex)
            {
                ViewData["Message"] = ex.Message;
            }
            finally
            {
                ktvPics.Dispose();
                ktvInfos.Dispose();
            }
            return RedirectToAction("Details", new { KTVNum = ktvNum });
        }

        [Authorize(Roles = "Administrator")]
        public string DeleteKTVPic(int id)
        {
            string ktvNum = Request.Form["KTVNum"];
            
            KTVPicResponsitory ktvPics = new KTVPicResponsitory();
            try
            {
                var ktvPic = ktvPics.GetById(id);
                if (ktvPic != null)
                {
                    try
                    {
                        System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + ktvPic.PictureUrl);
                    }
                    catch
                    {
                    }                   

                    ktvPics.Delete(ktvPic);
                    ktvPics.Save();                   
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                ktvPics.Dispose();
            }
            return "Đã xóa ảnh của KTV!";
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult UpdateShowHome(string ktvNum, string ktvId)
        {
            KTVInfoResponsitory ktvInfoRes = new KTVInfoResponsitory();
            try
            {
                if (!string.IsNullOrEmpty(ktvNum))
                {
                    KTVInfo ktvInfo = ktvInfoRes.GetByKTVNum(ktvNum).SingleOrDefault();
                    ktvInfo.ShowInHome = true;
                    ktvInfoRes.Save();
                }

                if (!string.IsNullOrEmpty(ktvId))
                {
                    KTVInfo ktvInfo = ktvInfoRes.GetById(ktvId);
                    ktvInfo.ShowInHome = false;
                    ktvInfoRes.Save();
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                ktvInfoRes.Dispose();
            }
            return RedirectToAction("ManagerHome");
        }

        #region  JSON
        public JsonResult GetKtvInfos()
        {
            KTVInfoResponsitory ktvRes = new KTVInfoResponsitory();
            try
            {
                var ktvs = from ktv in ktvRes.GetByRandom(10)
                           select new
                           {
                               ktv.Avartar,
                               BirthDate = string.Format("{0:dd/MM/yyyy}", ktv.BirthDate),
                               ktv.Height,
                               ktv.KTVId,
                               ktv.KTVNum,
                               ktv.Name,
                               ktv.Note,
                               ktv.Sex,
                               ktv.Size1,
                               ktv.Size2,
                               ktv.Size3,
                               ktv.Weight
                           }; ;

                return Json(ktvs.ToList(), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
            finally
            {
                ktvRes.Dispose();
            }
        }

        public JsonResult GetKtvNotShow()
        {
            KTVInfoResponsitory ktvRes = new KTVInfoResponsitory();
            try
            {
                var ktvs = from ktv in ktvRes.All()
                           where ktv.ShowInHome == false
                           select new
                           {                               
                               ktv.KTVId,
                               ktv.KTVNum,
                               ktv.Name,
                           }; ;

                return Json(ktvs.ToList(), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
            finally
            {
                ktvRes.Dispose();
            }
        }

        public JsonResult GetKtvInfoByNum(string num)
        {
            KTVInfoResponsitory ktvRes = new KTVInfoResponsitory();
            try
            {
                KTVInfo ktvInfo = ktvRes.GetByKTVNum(num).SingleOrDefault();
                var ktv = new
                {
                    ktvInfo.Avartar,
                    BirthDate = string.Format("{0:dd/MM/yyyy}", ktvInfo.BirthDate),
                    ktvInfo.Height,
                    ktvInfo.KTVId,
                    ktvInfo.KTVNum,
                    ktvInfo.Name,
                    ktvInfo.Note,
                    ktvInfo.Sex,
                    ktvInfo.Size1,
                    ktvInfo.Size2,
                    ktvInfo.Size3,
                    ktvInfo.Weight
                };

                return Json(ktv, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
            finally
            {
                ktvRes.Dispose();
            }
        }

        public JsonResult GetKtvPicsByNum(string num)
        {
            KTVPicResponsitory ktvPics = new KTVPicResponsitory();
            try
            {
                var pics = from p in ktvPics.GetByKtvNum(num)
                           select new
                           {
                               p.PictureUrl,
                               p.Note,
                               p.KTVId
                           };
                return Json(pics.ToList(), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
            finally
            {
                ktvPics.Dispose();
            }
        }

        public JsonResult GetListFirstKtvPic(int frm, int to)
        {
            MassageDBDataContext db = new MassageDBDataContext();
            try
            {
                if (db.KTVPics.Count() > 0)
                {
                    var ktvpics = (from kp in db.KTVPics
                                   join ki in db.KTVInfos on kp.KTVId equals ki.KTVId
                                   select new
                                   {
                                       ki.KTVNum,
                                       ki.Name,
                                       kp.PictureUrl
                                   });
                    ktvpics = ktvpics.Skip(frm - 1 < 0 ? 0 : frm - 1).Take(to - frm);
                    //.Skip(frm - 1).Take(to - frm);                    
                    return Json(ktvpics, JsonRequestBehavior.AllowGet);
                }
                return Json("Empty");
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }

        #endregion
    }
}
